package com.cqs.leetcode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 基于栈非递归实现：
 * 循环
 * 1 当前结点node非空: 先访问后入栈 将节点node指向左子树
 * 2 当前结点node 为null 出栈 将节点node指向右子树
 * 结束条件：node==null && 栈空
 *
 * Created by cqs on 2018/5/5.
 */
public class BinaryTreePreorderTraversal {


    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;
        Stack<TreeNode> stack = new Stack<>();
        TreeNode node = root;
        while (!stack.isEmpty() || node != null) {
            if (node != null) {
                list.add(node.val);
                stack.push(node);
                node = node.left;
            } else {
                node = stack.pop().right;
            }
        }
        return list;

    }
}
